package com.legolas.demo.web.controller;

import com.legolas.demo.domain.Resource;
import com.legolas.demo.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
@RequestMapping("/res")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(String name, String url, String description) {
        Resource resource = new Resource();
        resource.setName(name);
        resource.setUrl(url);
        resource.setDescription(description);
        resourceService.addResource(resource);
        return "redirect:/res/list";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(String name, String url, String description, int id) {
        Resource resource = new Resource();
        resource.setId(id);
        resource.setName(name);
        resource.setUrl(url);
        resource.setDescription(description);
        resourceService.updateResource(resource);
        return "redirect:/res/list";
    }

    @RequestMapping("/list")
    public String list(Model model) {
        List<Resource> resources = resourceService.queryAllResource();
        model.addAttribute("resList", resources);
        return "/shiro/res/list";
    }

    @RequestMapping("/update/{id}")
    public String update(@PathVariable int id, Model model) {
        Resource resource = resourceService.queryResourceById(id);
        model.addAttribute("res", resource);
        return "/shiro/res/update";
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String del(@PathVariable int id) {
        resourceService.deleteResourceById(id);
        resourceService.deleteRoleResourceByResourceId(id);
        return "redirect:/res/list";
    }
}
